<template>
  <el-button type="primary" plain @click="addClick">新增</el-button>
  <!-- 表格 -->
  <el-table :data="tableData">
    <el-table-column prop="name" label="Name" />
    <el-table-column prop="age" label="Age" />
    <el-table-column fixed="right" label="Operations" width="120">
      <template #default="scope">
        <el-button type="text" size="small" @click="delClick(scope)"
          >Delete</el-button
        >
        <el-button type="text" size="small" @click="editClick(scope)"
          >Edit</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <!-- 弹窗 -->
  <el-dialog v-model="dialogFormVisible" title="Shipping address">
    <el-form :model="form">
      <el-form-item label="Name" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="Age" :label-width="formLabelWidth">
        <el-input v-model="form.age" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="handleSubmit">Confirm</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import {
  getList,
  updatePeople,
  addPeople,
  delPeople,
} from "@/components/axiosTable";
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const tableData = ref();
let form = reactive({
  id: null,
  name: "",
  age: "",
});
/**
 * 重置form
 */
function resetForm() {
  form.id = null;
  form.name = "";
  form.age = "";
}
/**  打开弹窗  添加 */
function addClick() {
  dialogFormVisible.value = true;
  //   一定要记得把form重置，不然会有上次修改赋值的数据
  resetForm();
}
/**
 * 弹窗保存
 */
async function handleSubmit() {
  dialogFormVisible.value = false;
  //   修改
  if (form.id) {
    await updatePeople(form);
  } else {
    //新增
    let { id, ...data } = form;
    await addPeople(data);
  }
  let { data } = await getList();
  tableData.value = data;
}
// 删除
async function delClick({ row }) {
  await delPeople(row._id);
  let { data } = await getList();
  tableData.value = data;
}
/**  打开弹窗  修改 */
function editClick({ row }) {
  form.id = row._id;
  form.name = row.name;
  form.age = row.age;
  dialogFormVisible.value = true;
}

onMounted(async () => {
  let { data } = await getList();
  tableData.value = data;
});
</script>

<style lang="less"></style>
